package hu.codelab.lg.servicecenter.adapters;

import hu.codelab.lg.servicecenter.R;
import hu.codelab.lg.servicecenter.entities.Address;
import hu.codelab.lg.servicecenter.entities.ServiceCenter;

import java.util.List;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public final class ListAdapter extends BaseAdapter {

    private final List<ServiceCenter> serviceCenters;
    private final LayoutInflater inflater;
    private final Resources resources;
    private final Typeface font;

    public ListAdapter(final Activity activity, final List<ServiceCenter> serviceCenters) {
        this.serviceCenters = serviceCenters;
        inflater = activity.getLayoutInflater();
        resources = activity.getResources();
        font = Typeface.createFromAsset(activity.getAssets(), "helvetica_neue.ttf");
    }

    @Override
    public int getCount() {
        return serviceCenters.size();
    }

    @Override
    public ServiceCenter getItem(final int position) {
        return serviceCenters.get(position);
    }

    @Override
    public long getItemId(final int position) {
        return 0;
    }

    @Override
    public View getView(final int position, final View covertView, final ViewGroup parent) {
        TextView listItem = (TextView) covertView;

        if (listItem == null) {
            listItem = (TextView) inflater.inflate(R.layout.item_list, null);
            listItem.setTypeface(font);
        }

        final ServiceCenter serviceCenter = serviceCenters.get(position);
        final Address address = serviceCenter.getAddress();

        final SpannableStringBuilder builder = new SpannableStringBuilder();

        final SpannableString nameText = new SpannableString(serviceCenter.getName());

        final SpannableString addressText = new SpannableString(address.getZip() + " " + address.getCity() + ", " + address.getStreet() + " " + address.getNumber());
        addressText.setSpan(new RelativeSizeSpan(0.8f), 0, addressText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        addressText.setSpan(new ForegroundColorSpan(resources.getColor(R.color.lg_gray)), 0, addressText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        builder.append(nameText).append('\n').append(addressText);
        listItem.setText(builder);

        return listItem;
    }
}
